package com.serookie.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt的过滤器
 * @author kevintam
 * @version 1.0
 * @date 2021/3/21 23:04
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取的后端接口的token
        String header = request.getHeader(JwtTokenUtils.CLAIM_KEY_HEADER);
        //判断header是否为空，他的头是否是这个header
        if(header!=null && header.startsWith(JwtTokenUtils.CLAIN_KEY_tokenHead)){
            String token= header.substring(JwtTokenUtils.CLAIN_KEY_tokenHead.length());
            String username = jwtTokenUtils.getUserNameToken(token);
            //表示有token但未登录
            if(username!=null && null==SecurityContextHolder.getContext().getAuthentication()){
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //验证token是否有效，重新设置用户对象
               if(jwtTokenUtils.verificationToken(token,userDetails)){
                   UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                   authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                   SecurityContextHolder.getContext().setAuthentication(authenticationToken);
               }
            }
        }
        filterChain.doFilter(request,response);
    }
}
